package com.algo.core;

import com.algo.core.filter.RapidFilterChain;
import com.algo.core.netty.HttpNettyServer;
import com.algo.core.processor.DefaultRequestProcessor;
import com.algo.core.processor.HttpRequestQueue;
import com.algo.core.processor.RequestProcessor;
import org.apache.log4j.Logger;

import java.io.File;

/**
 * Server端容器类
 */
public class Container implements LifeCycle {

    private static final Logger logger = Logger.getLogger(Container.class);

    // 配置类
    private RapidSeverConfig rapidSeverConfig;

    private HttpNettyServer nettyServer;

    private HttpRequestQueue httpRequestQueue;

    private RequestProcessor requestProcessor;

    private RapidFilterChain filterChain;

    public Container(RapidSeverConfig rapidSeverConfig) throws Exception {
        this.rapidSeverConfig = rapidSeverConfig;
        httpRequestQueue = new HttpRequestQueue();

        try {
            // 初始化过滤器链，加载配置的过滤器
            filterChain = new RapidFilterChain();
        } catch (Exception e) {
            logger.error("filter chain init error ", e);
            throw e;
        }

        // 初始化
        initilize();
    }

    @Override
    public void initilize() {
        logger.info("container initilize, prepare create netty server and processor.");
        nettyServer = new HttpNettyServer(rapidSeverConfig, httpRequestQueue);
        requestProcessor = new DefaultRequestProcessor(rapidSeverConfig, httpRequestQueue, filterChain);
    }

    @Override
    public void start() {
        logger.info("prepare to start serevr");
        nettyServer.start();
        requestProcessor.start();
    }

    @Override
    public void shutdown() {
        logger.info("container has been shutdown, prepare to shutdown netty server");
        nettyServer.shutdown();
        requestProcessor.shutdown();
    }
}
